package com.joe.luckpan;

import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by Daojian on 2015/9/16.
 */
public class LuckPan extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    private SurfaceHolder mHolder;
    private Canvas mCanvas;

    /**
     * 用于绘制的线程
     */
    private Thread mThread;

    /**
     * 线程的控制开关
     */
    private boolean isRunning;

    /**
     * 盘块奖项
     */
    private String[] prizeNames = new String[]{
            "单反相机",
            "IPAD",
            "恭喜发财",
            "IPHONE",
            "服装一套",
            "恭喜发财"
    };

    /**
     * 盘块奖项图片
     */
    private int[] prizeImgs = new int[]{
            R.drawable.danfan,
            R.drawable.ipad,
            R.drawable.f015,
            R.drawable.iphone,
            R.drawable.meizi,
            R.drawable.f015
    };

    /**
     * 与图片对应的Bitmap数组
     */
    private Bitmap[] prizeImgBitmaps;

    /**
     * 盘块颜色
     */
    private int[] panColors = new int[]{
            0XFFFFC300,
            0XFFF17E01,
            0XFFFFC300,
            0XFFF17E01,
            0XFFFFC300,
            0XFFF17E01
    };

    /**
     * 盘块数量
     */
    private int panItemCount = 6;

    /**
     * 整个盘块的范围
     */
    private RectF mRange = new RectF();

    /**
     * 整个盘块的半径
     */
    private int mRadius;

    /**
     * 绘制盘块的画笔
     */
    private Paint mArcPaint;

    /**
     * 绘制文字的画笔
     */
    private Paint mTextPaint;

    /**
     * 盘块滚动速度
     */
    private double scrollwSpeed;

    private volatile int startAngle = 0;//volatile:保存线程之间变量的可见性

    /**
     * 判断是否点击了停止按钮
     */
    private boolean isShouldEnd;

    /**
     * 转盘的中心位置
     */
    private int arcCenter;

    /**
     * 这里以paddingLeft为准
     */
    private int mPadding;
    private Bitmap bitmapBg = BitmapFactory.decodeResource(getResources(), R.drawable.bg2);
    private float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());


    public LuckPan(Context context) {
        this(context, null);
    }

    public LuckPan(Context context, AttributeSet attrs) {
        super(context, attrs);

        mHolder = getHolder();

        mHolder.addCallback(this);

        //可获得焦点
        setFocusable(true);
        setFocusableInTouchMode(true);
        //设置常量
        setKeepScreenOn(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
        mPadding = getPaddingLeft();
        mRadius = width - mPadding * 2;
        arcCenter = mRadius / 2;
        setMeasuredDimension(width, width);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        //初始化盘块绘制的画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(true);
        mArcPaint.setDither(true);

        //初始化绘制文字的画笔
        mTextPaint = new Paint();
        mTextPaint.setColor(0xffffffff);
        mTextPaint.setTextSize(textSize);

        //初始化盘块的绘制范围
        mRange = new RectF(mPadding, mPadding, mPadding + mRadius, mPadding + mRadius);

        //初始化奖品图盘
        prizeImgBitmaps = new Bitmap[panItemCount];
        for (int i = 0; i < panItemCount; i++) {
            prizeImgBitmaps[i] = BitmapFactory.decodeResource(getResources(), prizeImgs[i]);
        }

        isRunning = true;
        mThread = new Thread(this);
        mThread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void run() {
        while (isRunning) {
            long start = System.currentTimeMillis();
            draw();
            long end = System.currentTimeMillis();
            if (end - start < 50) {
                try {
                    Thread.sleep(50 - (end - start));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void draw() {
        try {
            mCanvas = mHolder.lockCanvas();
            if (mCanvas != null) {
                //draw something
                //绘制背景
                drawBg();

                float tmpAngle = startAngle;
                float sweepAngle = 360 / panItemCount;

                for (int i = 0; i < panItemCount; i++) {
                    mArcPaint.setColor(panColors[i]);
                    //绘制盘块
                    mCanvas.drawArc(mRange, tmpAngle, sweepAngle, true, mArcPaint);

                    //绘制文本
                    drawText(tmpAngle, sweepAngle, prizeNames[i]);
                    tmpAngle += sweepAngle;
                }
            }
        } catch (Exception e) {

        } finally {
            if (mCanvas != null) {
                mHolder.unlockCanvasAndPost(mCanvas);
            }
        }
    }


    /**
     * 绘制背景
     */
    private void drawBg() {
        mCanvas.drawColor(0Xffffffff);
        mCanvas.drawBitmap(bitmapBg, null, new RectF(mPadding / 2, mPadding / 2, getMeasuredWidth() - mPadding / 2, getMeasuredHeight() - mPadding / 2), null);
    }

    /**
     * 绘制每个盘块的文本
     *
     * @param tmpAngle
     * @param sweepAngle
     * @param prizeName
     */
    private void drawText(float tmpAngle, float sweepAngle, String prizeName) {
        Path path = new Path();
        path.addArc(mRange, tmpAngle, sweepAngle);

        //利用水平偏移量让文字居中
        float textWidth = mTextPaint.measureText(prizeName);
        int hOffset = (int) (mRadius * Math.PI / panItemCount / 2 - textWidth / 2);
        //垂直偏移量
        int vOffset = mRadius / 2 / 6;
        mCanvas.drawTextOnPath(prizeName, path, hOffset, vOffset, mTextPaint);
    }


}
